<?php

namespace support\traits;

use support\spark\model\user\User;
use support\spark\model\user\UserLabelRelation;
use support\spark\model\user\UserLevel;

trait UserVipTrait
{
    /**
     * 计算vip优惠
     * @param $payAmount
     * @param $userId
     * @return array
     */
    public function calcUserVip($payAmount, $userId)
    {
        $vipDiscount = 0;
        $vipConf = getConfByType('shop_user_level');
        if ($vipConf['user_level_open'] != 1) {
            return dataReturn(0, 'success', $vipDiscount);
        }

        // 用户等级
        $userModel = new User();
        $userInfo = $userModel->getInfoByWhere([
            'id' => $userId
        ], ['vip_level']);
        if ($userInfo['vip_level'] == 0) {
            return dataReturn(0, 'success', $vipDiscount);
        }

        // 查询对应的折扣
        $userLevelModel = new UserLevel();
        $vipDiscountInfo = $userLevelModel->getInfoByWhere([
            'level' => $userInfo['vip_level']
        ], ['discount']);

        if (empty($vipDiscountInfo)) {
            $vipDiscountInfo['discount'] = 0;
        }

        $vipDiscount = round($payAmount - $payAmount * ($vipDiscountInfo['discount'] / 100), 2);

        return dataReturn(0, 'success', $vipDiscount);
    }

    /**
     * 关联用户标签
     * @param $labels
     * @param $userId
     */
    public function linkUserLabel($labels, $userId)
    {

        $labelArr = explode(',', rtrim($labels, ','));
        $userLabelRelationModel = new UserLabelRelation();
        $userLabels = $userLabelRelationModel->getAllList([
            ['user_id', '=', $userId],
            ['label_id', 'in', $labelArr]
        ], ['label_id']);

        $hasLabels = [];
        foreach ($userLabels as $vo) {
            $hasLabels[] = $vo['label_id'];
        }

        // 计算差集
        $newLabel = array_diff($labelArr, $hasLabels);
        $labelMap = [];
        foreach ($newLabel as $vo) {
            if(!$vo) continue;
            $labelMap[] = [
                'user_id' => $userId,
                'label_id' => $vo,
                'create_time' => now()
            ];
        }
        if($labelMap){
            $userLabelRelationModel->insertBatch($labelMap);
        }

    }
}
